﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;

namespace Simp.Interpreter
{
	/// <summary>Input control.  User will enter <c>Simp</c> functions.</summary>
	public partial class InputUserControl : UserControl
	{
		private readonly List<string> _functionContentList = new List<string>();
		private int _listPosition = 0;

		/// <summary>Constructor.</summary>
		public InputUserControl()
		{
			InitializeComponent();
		}

		#region NewFunction event
		private static readonly RoutedEvent NewFunctionEvent = EventManager.RegisterRoutedEvent(
				"NewFunction",
				RoutingStrategy.Bubble,
				typeof(RoutedEventHandler),
				typeof(InputUserControl));

		/// <summary>Raised when a new function is entered.</summary>
		public event RoutedEventHandler NewFunction
		{
			add { AddHandler(NewFunctionEvent, value); }
			remove { RemoveHandler(NewFunctionEvent, value); }
		}
		#endregion

		/// <summary>Returns the last function content.</summary>
		public string LastFunctionContent
		{
			get { return _functionContentList.Count == 0 ? null : _functionContentList[_functionContentList.Count - 1]; }
		}

		private void inputBox_KeyUp(object sender, KeyEventArgs e)
		{
			switch (e.Key)
			{
				case Key.Enter:
					OnKeyEnter();
					break;
				case Key.Up:
					OnKeyUp();
					break;
				case Key.Down:
					OnKeyDown();
					break;
			}
		}

		private void OnKeyEnter()
		{
			if (!string.IsNullOrEmpty(inputBox.Text))
			{
				_functionContentList.Add(inputBox.Text);
				_listPosition = _functionContentList.Count;
				inputBox.Text = string.Empty;
				RaiseEvent(new RoutedEventArgs(NewFunctionEvent));
			}
		}

		private void OnKeyUp()
		{
			if (_listPosition > 0)
			{
				--_listPosition;
				inputBox.Text = _functionContentList[_listPosition];
				inputBox.CaretIndex = inputBox.Text.Length;
			}
		}

		private void OnKeyDown()
		{
			if (_listPosition < _functionContentList.Count - 1)
			{
				++_listPosition;
				inputBox.Text = _functionContentList[_listPosition];
				inputBox.CaretIndex = inputBox.Text.Length;
			}
		}

		private void UserControl_Loaded(object sender, RoutedEventArgs e)
		{
			inputBox.Focus();
		}
	}
}